package org.redr.widgetGUI.core;

import java.util.HashMap;
import java.util.Map;

import org.redr.widgetGUI.settings.WidgetSettings;
import org.redr.widgetGUI.settings.WidgetState;
import org.redr.widgetGUI.settings.settingsTools.ItemsHandler;

import com.trolltech.qt.gui.QAbstractButton;
import com.trolltech.qt.gui.QButtonGroup;
import com.trolltech.qt.gui.QRadioButton;

public class RadioButtons extends WidgetState{
	private QButtonGroup buttons;
	private ItemsHandler itemsHandler;
	private Map<String, QRadioButton> buttonsMap = new HashMap<String, QRadioButton>();
	
	public QButtonGroup widget(){
		return buttons;
	}
	
	public RadioButtons(LayoutState p, WidgetSettings ws){
		super(p, ws);
		this.itemsHandler = ws.items("buttons");
		this.buttons = new QButtonGroup();
		//addWidget(buttons);
		_loadSettings();
		
	}
	
	private void _loadSettings(){
		
		
	}
	
	public String checkedText(){
		_setCheckedSettings();
		QAbstractButton b	=	 buttons.button(buttons.checkedId());
		if (b != null) return b.text();
		else return null;
	}
	
	private void _setCheckedSettings(){
		Integer checked	=	Integer.parseInt(_getSetting("checked", "-1"));
		QAbstractButton 	b	=	buttons.button(checked);
		if (b != null){
			b.setChecked(true);
		}
	}
	
	public void addButtons(Map<String, String> items){
		for (String k : items.keySet()){
			this.addButton(k, items.get(k));
		}
	}
	
	public void addButton(String key, String value){
		this.itemsHandler.addItem(key, value);
		QRadioButton w	=	new QRadioButton(value);
		this.buttonsMap.put(key, w);
		this.buttons.addButton(w);
		this.layout.addWidget(w);
	}
	
	public void clear(){
		this.itemsHandler.clear();
		this.buttonsMap.clear();
		for ( QAbstractButton w : this.buttons.buttons()){
			this.buttons.removeButton(w);
			this.layout.removeWidget(w);
		}
	}
	
	public void update(Map<String, String> items){
		// collect the checked id
		String checked = this.checkedId();
		this.clear();
		this.addButtons(items);
		this.setChecked(checked);
	}
	
	public String checkedId(){
		for(String k : this.buttonsMap.keySet()){
			QRadioButton button = this.buttonsMap.get(k);
			if (button.isChecked()) return k;
		}
		return null;
	}
	
	public void setChecked(String id){
		if (this.buttonsMap.keySet().contains(id)){
			this.buttonsMap.get(id).setChecked(true);
		}
	}
}
